<template>
  <!-- 标签模板 -->
  <div v-show="show">
    <div id="print_div" style="width: 80mm">
      <div style="margin: 0 auto; padding: 0 0 20mm">
        <p style="text-align: center; font-size: 16px; margin-bottom: 10px">
          {{ printHtml.title }}
        </p>
        <p
          v-for="(item, key) in printHtml.headTable"
          :key="key"
          style="font-size: 12px; margin-top: 5px"
        >
          <span>{{ item.name }}</span>
          <span style="margin-left: 5px">{{ item.value }}</span>
        </p>

        <table
          border="1"
          cellpadding="10"
          style="
            width: 100%;
            text-align: center;
            font-size: 12px;
            border-collapse: collapse;
            margin-top: 10px;
          "
        >
          <tbody>
            <tr v-for="(item, key) in printHtml.table" :key="key">
              <td
                :colspan="item.name2 ? 1 : 2"
                :style="{
                  width: `${item.name2 ? '80' : '60'}px`,
                  padding: '4px',
                  'white-space': 'nowrap',
                }"
              >
                {{ item.name }}
              </td>
              <td
                class="value"
                :colspan="item.name2 ? 1 : 2"
                style="min-width: 60px; padding: 4px; word-break: break-all"
              >
                {{ item.value }}
              </td>
              <td v-if="item.name2" style="width: 80px; padding: 4px">
                {{ item.name2 }}
              </td>
              <td
                v-if="item.name2"
                class="value"
                style="min-width: 60px; padding: 4px; word-break: break-all"
              >
                {{ item.value2 }}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="printingTemplate">
  import { defineExpose, ref, watch } from 'vue';

  // import lang from "../../lang";
  import { cloneDeep } from 'lodash-es';
  import dayjs from 'dayjs';
  import { t } from '@/i18n';
  import { useMixins } from '@/hooks/useMixins';
  import { getLodop } from '@/utils/lodopFuncs';

  interface Props {
    labelPrintTop: any;
  }

  const props = withDefaults(defineProps<Props>(), {
    labelPrintTop: () => 300,
  });

  const {
    // loadLangFn,
    language,
  } = useMixins();
  // loadLangFn(lang);
  const show = ref(false);
  const printData: any = ref(null);
  const waiting = ref(false);
  const printTaskID: any = ref(null);
  const existTaskID: any = ref(null);
  const printID: any = ref(null);
  const num: any = ref(null);
  const time: any = ref(null);

  const printHtml: any = ref({
    title: t('productionCenter.printTemplate.title'),
    headTable: [
      {
        prop: 'trayCode',
        name: t('productionCenter.printTemplate.trayNumber'),
        value: '',
      },
      {
        prop2: 'trayNum',
        name2: t('productionCenter.printTemplate.dangtuoNumber'),
        value2: '',
      },
    ],
    table: [
      {
        prop: 'orderCode',
        name: t('productionCenter.printTemplate.orderCode'),
        value: '',
        prop2: '',
        name2: '',
        value2: '',
      },
      {
        prop: 'customerName',
        name: t('productionCenter.printTemplate.customerName'),
        value: '',
        prop2: '',
        name2: '',
        value2: '',
      },
      {
        prop: 'materialCode',
        name: t('productionCenter.printTemplate.materialCode'),
        value: '',
        prop2: '',
        name2: '',
        value2: '',
      },
      {
        prop: 'materialName',
        name: t('productionCenter.printTemplate.materialName'),
        value: '',
        prop2: '',
        name2: '',
        value2: '',
      },
      {
        prop: 'version',
        name: t('productionCenter.printTemplate.version'),
        value: '',
        prop2: '',
        name2: '',
        value2: '',
      },
      {
        prop: 'materialStandards',
        name: t('productionCenter.printTemplate.materialStandards'),
        value: '',
        prop2: '',
        name2: '',
        value2: '',
      },
      {
        prop: 'templateNum',
        name: t('productionCenter.printTemplate.templateNum'),
        value: '',
        prop2: 'orderNum',
        name2: t('productionCenter.printTemplate.orderNum'),
        value2: '',
      },
      {
        prop: 'pileNum',
        name: t('productionCenter.printTemplate.pileNum'),
        value: '',
        prop2: 'totalTray',
        name2: t('productionCenter.printTemplate.totalTray'),
        value2: '',
      },
      {
        prop: 'machineName',
        name: t('productionCenter.printTemplate.machineName'),
        value: '',
        prop2: '',
        name2: '',
        value2: '',
      },
      // {
      //   prop: 'shiftName',
      //   name: t('productionCenter.labelsPrinting.printTemplate.shiftName'),
      //   value: '',
      //   prop2: '',
      //   name2: '',
      //   value2: ''
      // },
      // {
      //   prop: 'workers',
      //   name: t('productionCenter.labelsPrinting.printTemplate.workers'),
      //   value: '',
      //   prop2: '',
      //   name2: '',
      //   value2: ''
      // },
      // {
      //   prop: 'productTime',
      //   name: t('productionCenter.labelsPrinting.printTemplate.productTime'),
      //   value: '',
      //   prop2: '',
      //   name2: '',
      //   value2: ''
      // },
      {
        prop: 'customerDeliveryDate',
        name: t('productionCenter.printTemplate.customerDeliveryDate'),
        value: '',
        prop2: '',
        name2: '',
        value2: '',
      },
      {
        prop: 'remarks',
        name: t('productionCenter.printTemplate.remark'),
        value: '',
        prop2: '',
        name2: '',
        value2: '',
      },
      {
        prop: 'currentDate',
        name: t('productionCenter.printTemplate.printTime'),
        value: '',
        prop2: '',
        name2: '',
        value2: '',
      },
    ],
  });

  function setPrintHtmlFn(val) {
    printHtml.value = val;
  }

  // const companyName:any = inject('companyName');

  watch(
    () => printData,
    (val, _oldValue) => {
      if (val && val.value) {
        console.log(val);
        const newPrintHtml = cloneDeep(toRaw(printHtml.value));

        for (const item of newPrintHtml.headTable) {
          if (item.prop) {
            if (item.prop === 'printTime') {
              item.value = dayjs().format('YYYY-MM-DD HH:mm:ss') || '-';
            } else {
              item.value = val.value[item.prop] || '-';
            }
          }

          if (item.prop2) {
            if (item.prop2 === 'printTime') {
              item.value = dayjs().format('YYYY-MM-DD HH:mm:ss') || '-';
            } else {
              item.value2 = val.value[item.prop2] || '-';
            }
          }
        }

        for (const item of newPrintHtml.table) {
          if (item.prop) {
            if (item.prop === 'printTime') {
              item.value = dayjs().format('YYYY-MM-DD HH:mm:ss') || '-';
            } else {
              item.value = val.value[item.prop] || '-';
            }
          }

          if (item.prop2) {
            if (item.prop2 === 'printTime') {
              item.value2 = dayjs().format('YYYY-MM-DD HH:mm:ss') || '-';
            } else {
              item.value2 = val.value[item.prop2] || '-';
            }
          }
        }

        console.log(newPrintHtml);

        printHtml.value = newPrintHtml;
      }
    },
    { deep: true }
  );

  function setEnTime(date) {
    const dateList = date.split(' ');

    if (dateList.length === 2) {
      const ymdList = dateList[0].split('-');

      const hmsList = dateList[1].split(':');

      if (ymdList.length === 3 && hmsList.length === 3)
        return `${dateList[1]} ${ymdList[1]}/${ymdList[2]}/${ymdList[0]}`;
    }

    return date;
  }

  async function printFn(pData) {
    if (pData) {
      const data = cloneDeep(pData);

      if (language === 'en') {
        const { productTime = '', currentDate = '', customerDeliveryDate = '' } = data;

        if (productTime) data.productTime = setEnTime(productTime);

        if (currentDate) data.currentDate = setEnTime(currentDate);

        if (customerDeliveryDate) data.customerDeliveryDate = setEnTime(customerDeliveryDate);
      }

      printData.value = data;
    }

    return new Promise((resolve, reject) => {
      console.log('调用模板打印');
      nextTick(() => {
        printInit();

        LODOPPrintFn(resolve, reject);
      });
    });
  }

  function printInit() {
    waiting.value = false;

    printTaskID.value = null;

    existTaskID.value = null;

    printID.value = null;

    clearTimeout(time);

    num.value = null;

    time.value = null;
  }

  function LODOPPrintFn(resolve, reject) {
    const LODOP = getLodop();

    if (LODOP === 'loading' || !LODOP) {
      resolve(false);

      return;
    }

    if (!waiting.value) {
      const top =
        props.labelPrintTop && Number(props.labelPrintTop) && !isNaN(Number(props.labelPrintTop))
          ? Number(props.labelPrintTop)
          : 300;

      LODOP.PRINT_INIT(printHtml.value.title);

      LODOP.SET_PRINT_PAGESIZE(3, '80mm', '', '');

      LODOP.ADD_PRINT_HTM(
        top,
        '',
        '100%',
        '100%',
        (document.getElementById('print_div') as any).innerHTML
      );

      // LODOP.ADD_PRINT_HTM(300,'',"100%","100%",document.getElementById("print_div").innerHTML);

      LODOP.SET_PRINT_STYLEA(0, 'Left', 2);

      LODOP.SET_PRINT_MODE('CATCH_PRINT_STATUS', true);
      // const printTaskID = LODOP.PREVIEW();
      if (LODOP.CVERSION) {
        LODOP.On_Return_Remain = true;

        LODOP.On_Return = (TaskID, Value) => {
          if (TaskID == printTaskID.value) {
            printID.value = Value;

            if (Value !== '') {
              waiting.value = true;

              num.value = 2;

              time.value = setTimeout(() => {
                LODOPPrintFn(resolve, reject);
              }, 1000);
            }
          } else if (TaskID == existTaskID.value) {
            if (Value === '0') {
              printInit();

              console.log('跳出');

              resolve(true);
            } else {
              if (num.value !== 0) {
                num.value = num.value - 1;

                time.value = setTimeout(() => {
                  LODOPPrintFn(resolve, reject);
                }, 1000);
              } else {
                LODOP.SET_PRINT_MODE(
                  `CONTROL_PRINTER:${getPrinterIDfromJOBID(printID.value)}`,
                  'PURGE'
                );

                printInit();

                console.log('跳出');

                resolve(false);
              }
            }
          }

          // that.getStatusValue(TaskID,Value);
          // this.returnFn(TaskID,Value);
        };

        printTaskID.value = LODOP.PRINT();
      }
    } else {
      if (LODOP.CVERSION) {
        existTaskID.value = LODOP.GET_VALUE('PRINT_STATUS_EXIST', printID.value);
      } else {
        if (!LODOP.GET_VALUE('PRINT_STATUS_EXIST', printID.value)) {
          resolve(false);

          printInit();
        } // 以是否还在队列为准

        // setTimeout('PrintWaitLoop()', 1000);
      }
    }
  }

  function getPrinterIDfromJOBID(strJOBID) {
    const intPos = strJOBID.indexOf('_');

    if (intPos < 0) return strJOBID;
    else return strJOBID.substr(0, intPos);
  }

  defineExpose({
    printFn,
    setPrintHtmlFn,
  });
</script>

<style lang="less" scoped></style>
